# -*- coding: utf-8 -*-
# filename: handle.py

import web
import json
import re
import random
import urllib
import requests
from configcenter import configCenter
class Smscode(object):
    def POST(self):
        try:
            web.header("Access-Control-Allow-Origin", "*")
            web.header('content-type','text/json')
            webData = web.input()
            numbers = webData.mobile
            pattern1 = re.compile(r'[0-9]{11}')
            if pattern1.match(numbers):
                data = {"accesskey":"3565","secretkey":"56f52b8b8a8bde3a8cd4180ee471640dcf69a1ae"}
                data['mobile'] = numbers
                smscode = self.getRandomCode()
                data['content'] = "验证码: "+ smscode+"【西安交大MEM2018年会组委会】"
                url = "http://imlaixin.cn/Api/send/data/json?"
                r = requests.post(url + urllib.urlencode(data))
                rd = eval(r.text.replace('null', '"null"'))
                if rd['result'] == "01":
                    result = {'result': True, 'msg': '已发送'}
                    cc = configCenter()
                    config = cc.getConfig()
                    host = config.get("global", "ip")
                    port = config.get("global", "port")
                    user = config.get("global", "user")
                    pw = config.get("global", "password")
                    database = config.get("global", "database")
                    db = web.database(dbn='mysql', host=host, port=int(port), user=user, pw=pw, db=database)
                    cr = db.select('checks',  where="mobile = "+str(numbers))
                    if len(cr) == 0:
                        db.insert('checks', mobile=numbers,smscode=smscode)
                    else:
                        db.update('checks',where="mobile = "+str(numbers),smscode=smscode)
                    return json.dumps(result)
                else:
                    result = {'result': False, 'msg': '发送失败'}
                    return json.dumps(result)
        except Exception as e:
            return e.args

    def getRandomCode(self):
        code_list = []
        for i in range(6):
            code_list.append(str(random.randint(0,9)))
        return "".join(code_list)



